'''
Created on Apr 19, 2009

@author: Administrator
'''
from django.contrib import auth
from django.forms import forms
from django.shortcuts import get_object_or_404
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.utils.translation import ugettext_lazy as _
from com.ericyang.common.web.middleware import threadlocals
from com.ericyang.common.web import redirect, page404, response, error_response
from com.ericyang.groupshopping.product.models import Product
from com.ericyang.groupshopping.addressbook.models import  AddressBook
from com.ericyang.groupshopping.order import  *
from com.ericyang.groupshopping.order.models import GroupOrder, GroupOrderUser, GroupOrderVendor
from com.ericyang.groupshopping.order.forms import GroupOrderCreationForm, GroupOrderChangeForm, OrderVendorCreationForm


# user add into a order
@login_required
def user_add_or_remove_order(request, order_id):
    user = threadlocals.get_current_user()
    if not user.is_common_user():
        return error_response(_("Bad request"))
    
    order = get_object_or_404(GroupOrder, pk=order_id)
    if not order.is_changable():
        return response("order/order_error.html", {"order":order, "error":_("Can't update order!")})
    try:
        order_user = GroupOrderUser.objects.get(order__id=order_id, user__id=user.id)
        # order use already existed, then delete
        order_user.delete()
        return redirect("/order/view/" + order_id + "/")
    
    except GroupOrderUser.DoesNotExist:
        request.session[SESSION_ORDER_ID_KEY] = order_id
        addressbooks = AddressBook.objects.filter(user__id=user.id)
        return response("order/order_user_addressbook_selection.html",
                        {"order":order, "addressbooks":addressbooks})

@login_required
def user_save_order(request, book_id):
    user = threadlocals.get_current_user()
    if not user.is_common_user():
        return error_response("Bad request")
    
    order_id = request.session[SESSION_ORDER_ID_KEY]
    order = get_object_or_404(GroupOrder, pk=order_id)
    if not order.is_changable():
        return response("order/order_error.html", {"order":order, "error":"Can't update order!"})
    
    try:
        order_user = GroupOrderUser.objects.get(order__id=order_id, user__id=user.id)
        # order use already existed, then delete
        order_user.delete()
    except GroupOrderUser.DoesNotExist:   
        order_user = GroupOrderUser()
        
    order_user.order = get_object_or_404(GroupOrder, pk=order_id)
    order_user.address_book = get_object_or_404(AddressBook, pk=book_id)
    order_user.user = threadlocals.get_current_user()
    
    order_user.save()
    
    return redirect("/order/user/orderlist/")

# a user or vendor quited a order
@login_required
def quit_order(request, order_id):
    user = threadlocals.get_current_user()
    order = get_object_or_404(GroupOrder, pk=order_id)
    if user.is_common_user():
        order_user = order.get_order_user(user.id)
        if order_user != None:
            order_user.quit_order()
                
    else:
        if user.is_company_user():
            order_vendor = order.get_order_vendor(user.id)
            if order_vendor != None:
                order_vendor.quit_order()
    
    return view_order(request, order_id)
# add vender
@login_required
def add_vender(request, order_id):
    user = threadlocals.get_current_user()
    if not user.is_company_user():
        return error_response(_("Bad request"))
    
    order = get_object_or_404(GroupOrder, pk=order_id)
    try:
        order_vendor = GroupOrderVendor.objects.get(order__id=order_id, user__id=user.id)
        return redirect("/order/view/" + order_id + "/")
    except GroupOrderVendor.DoesNotExist:   
        if request.method == "POST":
            form = OrderVendorCreationForm(order, request.POST)
            if form.is_valid():
                vendor = form.save()
                return view_order(request, order_id)
        else :
            form = OrderVendorCreationForm(order)
        
        return response("order/vendor_edit.html", {"form":form, "order":order})

# user vote for one vendor
@login_required
def user_vote(request, order_id, vendor_id):
    user = threadlocals.get_current_user()
    order = get_object_or_404(GroupOrder, pk=order_id)
    if not order.is_handling():
         return error_response(_("Bad request"))
    order_user = order.get_order_user(user.id)
    order_vendor = order.get_order_vendor_by_id(vendor_id)
    if order_user == None or order_vendor == None:
         return error_response(_("Bad request"))
    order_user.vote(order_vendor)
    return view_order(request, order_id)
    
# list orders of one product
@login_required
def list_product_orders(request, product_id):
    product = get_object_or_404(Product, pk=product_id)
    orders = GroupOrder.objects.filter(product__id=product_id)
    return response("order/order_list.html", {"orders":orders, "product":product})
    
# list group order
@login_required
def list_user_order(request):
    user = threadlocals.get_current_user()
    orders = (order_user.order for order_user in GroupOrderUser.objects.filter(user__id=user.id)[:5])
    return response("order/order_list.html", {"orders":orders})

# list group order
@login_required
def list_order(request, status=None):
    if status != None and GroupOrder.is_valid_status(status):
        key = GroupOrder.get_status_value(status)
        orders = GroupOrder.objects.filter(status=key)[:10]
    else:
        orders = GroupOrder.objects.filter(status__lte="2")[:10]
        #orders = GroupOrder.objects.filter(status="3")[:10]
    return response("order/order_list.html", {"orders":orders})

# view group order
@login_required
def view_order(request, order_id):
    user = threadlocals.get_current_user()
    order = get_object_or_404(GroupOrder, pk=order_id)
    
    order_user = order.get_order_user(user.id)
    order_vendor = order.get_order_vendor(user.id)
    
    return response("order/order_view.html", {"order":order,
                                               "order_user":order_user,
                                               "order_vendor":order_vendor})
# create group order
@login_required
def create_order(request, product_id):
    product = get_object_or_404(Product, pk=product_id)
    if request.method == "POST":
        form = GroupOrderCreationForm(product, request.POST)
        if form.is_valid():
            order = form.save()
            return list_order(request)
    else :
        form = GroupOrderCreationForm(product)
    
    return response("order/order_edit.html", {"form":form, "product":product})

# edit a group order
@login_required
def edit_order(request, order_id):
    order = get_object_or_404(GroupOrder, pk=order_id)
    if request.method == "POST":
        form = GroupOrderChangeForm(order, request.POST)
        if form.is_valid():
            order = form.save()
            return response("order/order_operation_result.html")
    else :
        # form = GroupOrderChangeForm(order)
        form = GroupOrderChangeForm(order)
    
    return response("order/order_edit.html", {"form":form, "product":order.product})

@login_required
def delete_order(request, order_id):
    order = get_object_or_404(GroupOrder, pk=order_id)
    user = threadlocals.get_current_user()
    if user.id == order.createUser.id:
        order.delete()
    return list_order(request)

@login_required
def cancel_order(request, order_id):
    order = get_object_or_404(GroupOrder, pk=order_id)
    if order.is_cancelable():
        order.cancel()
        return view_order(request, order_id)
    else :
        return error_response(_("The order can't be canceled!"))


@login_required
def stop_inviting(request, order_id):
    order = get_object_or_404(GroupOrder, pk=order_id)
    if order.is_inviting() and order.is_belong() and order.is_can_stop_inviting():
        order.stop_inviting()
        return view_order(request, order_id)
    else :
        return error_response(_("The order can't be stoped!"))
    
@login_required
def set_charging(request, order_id):
    order = get_object_or_404(GroupOrder, pk=order_id)
    if order.is_chargable():
        order.set_charging()
        return view_order(request, order_id)
    else :
        return error_response(_("The order can't be set to charging!"))
    
@login_required
def success_order(request, order_id):
    order = get_object_or_404(GroupOrder, pk=order_id)
    if order.is_charging() and order.is_belong():
        order.set_success()
        return view_order(request, order_id)
    else :
        return error_response(_("The order can't be set to success!"))
    
@login_required
def failed_order(request, order_id):
    order = get_object_or_404(GroupOrder, pk=order_id)
    if order.is_charging() and order.is_belong():
        order.set_failed()
        return view_order(request, order_id)
    else :
        return error_response(_("The order can't be set to failed!"))

def vote_order_vendor(request, order_id, vendor_id):
    user = threadlocals.get_current_user()
    order = get_object_or_404(GroupOrder, pk=order_id)
    
    order_user = order.get_order_user(user.id)
    if order_user == None:
        return error_response(_("You can't vote for this order!"))
    order_vendor = order.get_order_vendor(vendor_id)
    if order_vendor == None:
        return error_response(_("The vendor is not exist or has exited this order!"))
    if not order.is_handling():
        return error_response(_("This order can't vote for the monent!"))
    order_user.selected_vendor = order_vendor
    order_user.save()
    return view_order(request, order_id)
